<?php

namespace App\Models;

use Illuminate\Foundation\Auth\User as Authenticatable;
use Tymon\JWTAuth\Contracts\JWTSubject;

class User extends Authenticatable implements JWTSubject
{

    protected $fillable = [
        'name', 'openID', 'sex', 'avatar', 'email'
    ];

    protected $hidden = [
        'id', 'created_at', 'updated_at'
    ];

    //自定义路由键名
    public function getRouteKeyName()
    {
        return 'openID';
    }

    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    public function getJWTCustomClaims()
    {
        return [];
    }

    //发布的订单
    public function orders(){
        return $this->hasMany(Order::class,'provider', 'openID');
    }

    //接收的订单
    public function orders_receive(){
        return $this->hasMany(Order::class,'receiver','openID');
    }

    public function friends(){
        return $this->belongsToMany(User::class,'friends','user_id','friend_id');
    }

    //根据openid获取用户实例
    public static function getInfoByOpenid($openid){
        $user = User::where('openID',$openid)->first();
        return $user;
    }

    //添加好友
    public function follow($friend_id){
        $this->friends()->sync($friend_id,false);
    }

    //删除好友
    public function unfollow($friend_id){
        $this->friends()->detach($friend_id);
    }

}
